package org.example;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

public class AdbUtil {
    public static List<String> getDevices() {
        return null;
    }

    public static boolean pushFile(String deviceSerial, String localPath, String remotePath) {
        return false;
    }

    // 模拟执行 adb pull 命令
    public static boolean pullFile(String deviceSerial, String remotePath, String localPath) throws IOException {
        // 拼接 adb pull 命令
        String command = "adb pull \"" + remotePath + "\" \"" + localPath + "\"";
        System.out.println("Executing: " + command);
        // 执行命令
        Process process = Runtime.getRuntime().exec(command);
        try {
            process.waitFor(); // 等待命令执行完成

            if (process.exitValue() == 0) {
                return true;
            } else {
                InputStream errorStream = process.getErrorStream();
                StringWriter out = new StringWriter();
                IOUtils.copy(errorStream, out, "UTF-8");
                System.err.println("Error pulling file: " + out.toString());
                errorStream.close();
                out.close();
            }
        } catch (Exception e) {
            System.err.println("异常命令：" + command);
            e.printStackTrace();
        }
        return false;
    }

    public static List<String> listFiles(String deviceSerial, String remotePath) {
        return null;
    }

    public static boolean deleteFile(String deviceSerial, String remotePath) {
        return false;
    }
    // 其他操作

    public static List<String> listFilesOnDevice(String remotePath) {
        List<String> list = new LinkedList<>();
        try {
            ProcessBuilder builder = new ProcessBuilder("adb", "shell", "ls", "-lh", remotePath);
            //ProcessBuilder builder = new ProcessBuilder("adb", "shell", "ls", "-m", remotePath);
            Process process = builder.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;

            boolean isFirstLine = true;
            System.out.println("Files in " + remotePath + ":");
            while ((line = reader.readLine()) != null) {
                //System.out.println(line);
                if (isFirstLine) {
                    isFirstLine = false;
                    continue;
                }
                list.add(line);
            }

            process.waitFor();

            if (process.exitValue() != 0) {
                System.err.println("Error listing files.");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return list;
    }
}
